import axios from 'axios';
const HTTP =  '/';
const utils = {
    HREF: HTTP + 'wap/index.html#/',
    //HREF: 'http://feiyu.zxy.egaopa.com/#/',
    //HREF: 'http://localhost:8080/#/',
    AJAX_SRC: HTTP + 'Api/',
    FILL: 'http://file.jiaoxin-tech.cn/',
    Ua: window.navigator.userAgent.toLowerCase(),
    ajaxFlag: true
};

/*
* 判断是否再微信中
* */
utils.isWeiXin = ()=>{
    return utils.Ua.match(/MicroMessenger/i) == 'micromessenger' ? true : false;
};

/*
* 判断是否在App中
* */
utils.isFeiYu = ()=>{
    return window.feiyu;
};

/*
 * 判断字符串是否以指定字符串开头
 */
String.prototype.startWith = function(compareStr){
    return this.indexOf(compareStr) == 0;
};
/*
 * 判断字符串是否以指定字符串结尾
 */
String.prototype.endWith = function(compareStr){
    return this.length < compareStr.length ? false : this.lastIndexOf(compareStr) == this.length - compareStr.length;
};

/*
 * 获取指定name的SessionStorage值
 * name: 键
 */
utils.getSessionStorage = function(name){
    let obj = window.sessionStorage.getItem(name);
    return obj && (obj.startWith('{') || obj.startWith('[')) ? eval('(' + obj + ')') : obj;
};

/*
 * 设置SessionStorage值
 * name: 键
 * value: 值
 */
utils.setSessionStorage = function(name, value){
    value = typeof value != 'object' ? value : JSON.stringify(value);
    window.sessionStorage.setItem(name, value);
};

/*
 * 删除SessionStorage值
 * name: 键,不传则清楚所有
 */
utils.deleteSessionStorage = function(name){
    if(name) window.sessionStorage.removeItem(name);
    else {
        let storage = window.sessionStorage;
        for(let i in storage){
            window.sessionStorage.removeItem(i);
        }
    }
};

/*
 * 获取指定name的localStorage值
 * name: 键
 */
utils.getLocalStorage = function(name){
    let obj = window.localStorage.getItem(name);
    return obj && (obj.startWith('{') || obj.startWith('[')) ? eval('(' + obj + ')') : obj;
};

/*
 * 设置localStorage值
 * name: 键
 * value: 值
 */

utils.setLocalStorage = function(name, value){
    value = typeof value != 'object' ? value : JSON.stringify(value);
    window.localStorage.setItem(name, value);
};

/*
 * 删除Cookie值
 * name: 键,不传则清楚所有
 */
utils.deleteLocalStorage = function(name){
    if(name) window.localStorage.removeItem(name);
    else window.localStorage.clear();
};

/*
* 公用加载中
* */
utils.loading = (flag=true)=>{
    let loading = document.getElementById('loading');
    if(!flag){
        if(!loading) return;
        loading.parentNode.removeChild(loading);
        return;
    }
    let app = document.getElementById('app');
    if(loading) return;
    let loadingEle = document.createElement('div');
    loadingEle.id = 'loading';
    loadingEle.className = 'loadingWrap';
    loadingEle.innerHTML = '<div class="loadingInner"></div>';
    app.appendChild(loadingEle);
};

/*
* 展示提示信息
* tips: 提示信息
* */
utils.showTips = (tips='错误提示')=>{
    if(document.getElementById('SucTips')) return;
    let div = document.createElement('div');
    div.id = 'SucTips';
    div.innerHTML = '<span>' + tips + '</span>';
    document.getElementById('app').appendChild(div);
    let timer = setTimeout(()=>{
        document.getElementById('SucTips').parentNode.removeChild(document.getElementById('SucTips'));
        clearTimeout(timer);
    },4000);
};
/*
* 公用弹框
* that: 当前组件
* obj:{
*  title: '标题',
*  content: '内容',
*  ensure: fn,
*  cancel: fn 可选
* }
* */
utils.modal = (that , obj)=>{
    let app = document.getElementById('app') ,
        modal = document.getElementById('modal');
    if(modal) modal.parentNode.removeChild(modal);
    let modalEle = document.createElement('div');
    modalEle.id = 'modal';
    modalEle.className = 'modalWrap flex-container';
    modalEle.innerHTML = '<div class="modal-inner">' +
        '<h3>' + ( obj.title ? obj.title : '' ) + '</h3>' +
        '<div class="modal-cot">' + obj.content + '</div>' +
        '<div class="modal-btns flex-container">' +
        '<a href="javascript:;" id="modalSure">确定</a>' +
        (obj.cancel ? '<a href="javascript:;" id="modalCancel">取消</a>' : '') +
        '</div>' +
        '</div>';
    app.appendChild(modalEle);
    document.getElementById('modalSure').onclick = function(){
        document.getElementById('modal').parentNode.removeChild(document.getElementById('modal'));
        obj.ensure.call(that);
    };
    if(!document.getElementById('modalCancel')) return;
    document.getElementById('modalCancel').onclick = function(){
        document.getElementById('modal').parentNode.removeChild(document.getElementById('modal'));
        obj.cancel.call(that);
    }
};

/*
* 表单基本验证码
* verifyType: 验证类型
* val: 需要验证的值
* */
utils.validate = (verifyType , val , tips)=>{
    let msg , isCorrect;
    switch(verifyType){
        case 'noNull' :
            isCorrect = val;
            msg = tips + '不能为空!';
            break;
        case 'phone' :
            isCorrect = /^1\d{10}$/.test(val); //手机号
            msg = '请填写正确的手机号!';
            break;
        case 'code':
            isCorrect = /^\d{6}$/.test(val); //验证码
            msg = '请填写正确的验证码!';
            break;
        case 'psdLen':
            isCorrect = val.length >= 6 && val.length <= 12; //用户密码
            msg = '密码必须6-12位之间哦!';
            break;
        case 'idCard':
            isCorrect = /^\d{15}|\d{}18$/.test(val); //身份证
            msg = '请填写正确的身份证号码!';
            break;
        case 'bankCard':
            isCorrect = /^([1-9]{1})(\d{14}|\d{18})$/.test(val); //银行卡
            msg = '请填写正确的银行卡号!';
            break;
        default:
            isCorrect = true;
    }
    if(!isCorrect) utils.showTips(msg);
    return isCorrect;
};

/*
* 图片统一增加onErr事件
* */
utils.imgErr = function(ele){
    ele = document.querySelector(ele);
    let imgErrFun = function(){
        if(this.getAttribute('mark')){
            this.onerror = null;
            return;
        }
        this.setAttribute('mark', 1);
        let defaultSrc = this.getAttribute('defaultSrc');
        defaultSrc = 'http://feiyutiyu.cn/Wap/static/default/' + defaultSrc;
        this.src = defaultSrc;
    };
    if(ele && ele.tagName.toLowerCase() == 'img'){
        $(ele).bind('error',imgErrFun);
        return;
    }
    ele = ele || document;
    let imgs = ele.querySelectorAll('img');
    for(let i = 0 ; i < imgs.length ; i++){
        imgs[i].onerror = imgErrFun;
    }
};

/*
* 请求前处理
* */
axios.interceptors.request.use(config => {
    let pageId = location.href.split('#/')[1];
    if(pageId && pageId != 'userCenter' && pageId != 'wallet') utils.loading();
    return config;
}, error => { return Promise.reject(error) });

/*
* 请求完成处理
* */
axios.interceptors.response.use(response => {
    utils.loading(false);
    return response;
}, error => { return Promise.reject(error) });

/*
* 处理App、微信、h5登录信息失效的问题
* loginData：App中存储用于登录的信息
* */
utils.handleLogin = (response)=>{
    /*
    * 如果当前环境在App内
    * */
    if(utils.isFeiYu()){
        let params = JSON.parse(window.feiyu.deviceLogin());
        utils.ajax({
            url: utils.AJAX_SRC + 'Login/Device1',
            params: params,
            success(result){
                utils.ajaxFlag = true;
                if (result.errcode == 0) {
                    utils.setLocalStorage('token' , result.data.token);
                    utils.ajax(response);
                    window.feiyu.setToken(result.data.token);
                    return;
                }
                location.replace(utils.HREF + 'login?backurl=' + encodeURIComponent(location.href));
            }
        });
        return;
    }
    /*
    * 如果在微信环境中
    * */
    if(utils.isWeiXin()){
        utils.ajax({
            url: utils.AJAX_SRC + 'Weixin/OAuth',
            params:{ backurl : location.href },
            success(result){
                utils.ajaxFlag = true;
                if (result.errcode == 0){
                    location.replace(result.href);
                }
            }
        });
        return;
    }
    /*
    * 在其他环境中
    * */
    location.replace(utils.HREF + 'login?backurl=' + encodeURIComponent(location.href));
    utils.ajaxFlag = true;
};

/*
* url: 请求地址
* params: 请求参数{name: 'lee' , age: 19}
* method: 请求类型，默认post
* */
utils.ajax = (response)=>{
    response.params = response.params || {};
    let token = utils.getLocalStorage('token');
    if(token) response.params.token = token;
    /*
    * 处理请求参数
    * */
    let params = new URLSearchParams();
    for(let i in response.params){ params.append(i , response.params[i]);}
    response.params = params;
    /*
    * 处理请求参数
    * */
    axios({
        url: response.url,
        method: response.method || 'post',
        params: params
    }).then(res=>{
      let data = res.data;
      if(data.errcode == -2){
          if(!utils.ajaxFlag) return;
          utils.ajaxFlag = false;
          utils.handleLogin(response);
          return;
      }
      if(response.success){
          response.success(data);
      }
    }).catch(err=>{
       if(response.error) response.error(err);
    });
};

/*
* 发送验证码
* that：当前vue实例
* params: 参数
* src: 请求地址 //Register/sendCode
* */
utils.sendCode = (that , params , src)=>{
    if(!that.isSendCode) return;
    if(!utils.validate('phone' , params.phone)) return;
    //民生银行
    if(src == 'Minsheng/getMobileCode'){
        params.MobilePhone = params.phone;
        delete params.phone;
    }
    utils.ajax({
        url: utils.AJAX_SRC + src,
        params: params,
        success(result){
            if(result.errcode < 0){
                utils.showTips(result.errmsg);
                return;
            }
            if(src == 'Minsheng/getMobileCode'){
                that.codeId = result.data.MessageTaskId;
            }else{
                that.codeId = result.data.codeId;
            }
            that.timeTips = '60s后重新获取';
            utils.showTips('验证码已发送');
            let counts = 60;
            let timer = setInterval(()=>{
                counts--;
                that.timeTips = counts + 's后重新获取';
                if(counts <= 0 ){
                    that.timeTips = '重新获取验证码';
                    clearInterval(timer);
                }
            },1000);
        }
    });
};

/*
* 轮播图渲染
* */
utils.swiper = (ele ,Swiper)=>{
    if(this[ele]) this[ele].destroy();
    this[ele] = new Swiper(ele, {
        autoplay: {
            disableOnInteraction: false,
        },
        loop: true,
        pagination:{
            el: '.swiper-pagination'
        }
    })
};

/*
* 上传方法
* that: 当前vue实例
* ele: 上传input
* fn：上传回调函数
* */
utils.upload = (that , ele , fn )=>{
    utils.loading();
    new Upyun({
        bucket: 'topman-upyun',
        operator: 'admin',
        getSignatureUrl: 'https://xcx.egaopa.com/Api/upyun/index',
        opts: { 'notify-url': 'http://feiyu.test.jiaoxin-tech.cn/Api/test/upyun' }
    }).upload({
        localPath: document.getElementById(ele).files[0],
        remotePath: document.getElementById("remotePath").value,
        success(res){
            utils.loading(false);
            fn.call(that , res);
        },
        error(err){
            utils.loading(false);
            utils.showTips('图片上传失败');
        }
    })
};

/*
* 初始化密码键盘boardData
* that：当前vue实例
* inputs: 输入框列表
* boardWrap: 键盘盒子列表
* randomData: 密码键盘所需的随机数、流水号等等
* */
utils.initKeyBoard = (boardData)=>{
    let RSA_PUBLIC_KEY = "308187028181009BF03D2FC10218A09FED2D4CFB5121E840DAF4CC0F75B06D5944C45AA0A90DBBBEE5392415F0C2BD4492C7DEF7F23ABDD31777495CF585B97D0904B355041EE440E72A4927EB71711E699635908F3A76C5456C64E0D24B1AF3E0E7311E12C880EB6EA42E2A5A2AE77A2581EBD7C3618B44E97DF9EB555EE3098AD2EC5A889001020103";
    let RSA_PUBLIC_KEY_SIG = "94BBFE900BD1E081C28C5A315C66B661B191570AB985EB9B0280DE0C490756AF242769EB671287B429E5C397FEC0DA2A8ED1287B3DA84BF8548EE15365AAD671CBC5CD148433CAC55CDBB4E7A285C43DC926197BA0E7EEBA18482E5F283337D0F080BBF43B583D00219F2450862517548BF7033927961FDD4ABB2A3C6DA39061";
    let inputs = boardData.inputs;
    let that = boardData.that;
    let boardWrap = boardData.boardWrap;
    for(let i = 0 ; i < inputs.length ; i++){
        let eleStr = inputs[i] ,
             pEleStr = boardWrap[i];
        that[eleStr] = new CFCAKeyboard(pEleStr , KEYBOARD_TYPE_DIGITAL);
        that[eleStr].bindInputBox(eleStr);
        that[eleStr].setPublicKey(RSA_PUBLIC_KEY , RSA_PUBLIC_KEY_SIG ,eleStr);
        that[eleStr].setMaxLength(6 ,eleStr);
        that[eleStr].setMinLength(6 ,eleStr);
        that[eleStr].hideKeyboard();
        document.getElementById(eleStr).onclick = function(){
            hideKeyBoard(eleStr , i);
            setRandom(eleStr);
            that.showPwdMask = true;
        };
        that[eleStr].setDoneCallback(function(e){
            that.showPwdMask = false;
        });
    }
    //当前其他的所有键盘
    function hideKeyBoard(eleStr , i){
        inputs.forEach(function(item , index){
            if(i !== index){
                that[eleStr].hideKeyboard();
            }
        })
    }
    //动态设置密码随机数
    function setRandom(eleStr){
        if(boardData.randomData){
            that[eleStr].setServerRandom(boardData.randomData.Random , eleStr);
            that[eleStr].showKeyboard();
            return;
        }
        utils.ajax({
            url: utils.AJAX_SRC + 'Minsheng/getRandom',
            success(result){
                if(result.errorCode < 0){
                    utils.showTips(result.errormsg);
                    return;
                }
                that[eleStr].setServerRandom(result.data.Random , eleStr);
                that[eleStr].showKeyboard();
                boardData.randomData = result.data;
            }
        })
    }
};

/*
* 初始化支付密码
* that: 当前vue实例
* fn: 密码输入完回调
* showPwdModal: 输入密码盒子
* */
utils.getPwdModal = (that , fn)=>{
    let RSA_PUBLIC_KEY = "308187028181009BF03D2FC10218A09FED2D4CFB5121E840DAF4CC0F75B06D5944C45AA0A90DBBBEE5392415F0C2BD4492C7DEF7F23ABDD31777495CF585B97D0904B355041EE440E72A4927EB71711E699635908F3A76C5456C64E0D24B1AF3E0E7311E12C880EB6EA42E2A5A2AE77A2581EBD7C3618B44E97DF9EB555EE3098AD2EC5A889001020103";
    let RSA_PUBLIC_KEY_SIG = "94BBFE900BD1E081C28C5A315C66B661B191570AB985EB9B0280DE0C490756AF242769EB671287B429E5C397FEC0DA2A8ED1287B3DA84BF8548EE15365AAD671CBC5CD148433CAC55CDBB4E7A285C43DC926197BA0E7EEBA18482E5F283337D0F080BBF43B583D00219F2450862517548BF7033927961FDD4ABB2A3C6DA39061";
    let exitBord = document.getElementById('NumberKeyboard');
    if(exitBord) exitBord.innerHTML = '';
    that['keyboard'] = null;
    that['keyboard'] = new CFCAKeyboard('NumberKeyboard' , KEYBOARD_TYPE_DIGITAL);
    let RandomData = null;
    that['keyboard'].bindInputBox('SIPBox');
    that['keyboard'].setPublicKey(RSA_PUBLIC_KEY , RSA_PUBLIC_KEY_SIG ,'SIPBox');
    that['keyboard'].showKeyboard();
    that['keyboard'].setMaxLength(6 ,'SIPBox');
    that['keyboard'].setMinLength(6 ,'SIPBox');
    utils.ajax({
        url: utils.AJAX_SRC + 'Minsheng/getRandom',
        success(result){
            if(result.errorCode < 0){
                utils.showTips(result.errormsg);
                return;
            }
            let data = result.data;
            that['keyboard'].clearInputValue();
            that['keyboard'].setServerRandom(data.Random , 'SIPBox');
            RandomData = data;
            that.showPwdModal = true;
            that['keyboard'].setDoneCallback(function(e){
                let val = that['keyboard'].getEncryptedInputValue('SIPBox');
                if(val == '01031421@null'){
                    that['keyboard'].showKeyboard();
                    utils.showTips('请继续输入密码!');
                    return;
                }
                fn.call(that , val , RandomData , that['keyboard']);
                that.showPwdModal = false;
            });
        }
    });
};

/*
* 处理多级联动层级关系
* data: 需要处理的多层数据
* */
utils.hanMultistage = (data)=>{
    let level = 0;
    function m(list){
        for(let i = 0 ; i < list.child.length ; i++){
            list.child[i].level = list.level + 1;
            if(list.child[i].child){
                m(list.child[i]);
            }
        }
    }
    for(let j = 0 ; j < data.length ; j++){
        data[j].level = 1;
        level = 1;
        if(data[j].child) m(data[j]);
    }
};


export default utils;


